$(function() {
	//alert(111)
        // 全选标记
        var checkFlag = 0;
        viewTh();

        // 日期选择
        $('.edit-modal').on('focus', '.e-c-date', function() {
            console.log(1111)
            $('.e-c-date').fdatepicker();
        })
        $('.edit-modal').on('focus', '.e-i-date', function() {
            $('.e-i-date').fdatepicker();
        })
        $('.edit-modal').on('focus', '.e-b-date', function() {
            $('.e-b-date').fdatepicker();
        })
        $('.edit-modal').on('focus', '.e-s-date', function() {
            $('.e-s-date').fdatepicker();
        })

        //打开详情模态框
        $('.this-table').on('click', '.view-info', function() {
                fadeModal('.info-modal');
                //前端数据
                var id = $(this).data('id'); //项目id
                $('.view-modal').data('id', id);
                // //------------------------------------------------
                var options = getBASEGETAJAX();
                options.url = "/epi/finance/" + id;
                options.success = function(data) {
                    console.log(data);
                    var myTemplate = Handlebars.compile($("#three-tip-info-template").html());
                    $('.three-tip-info').html(myTemplate(data));

                    fadeModal('.info-modal');

                };
                options.error = function() {
                    setAlert('系统繁忙，请刷新重试');
                };
                $.ajax(options);

            })
            /**
             * [查看详情确定]
             */
        $('.i-btn').click(function() {
            $('.info-modal,.mask').fadeOut();
        })

        /**
         * [修改财务信息模态框]
         */
        $(document).on('click', '.edit-info', function() {
                //edit-info
                var id = $(this).data("id");
                console.log(id);
                $('.edit-info-div').data("id", id);
                var options = getBASEGETAJAX();
                options.url = "/epi/finance/" + id;
                options.success = function(data) {
                    console.log(data);
                    var myTemplate = Handlebars.compile($("#money-info-template").html());
                    console.log(myTemplate(data))
                    $('.edit-info-div').html(myTemplate(data));
                    fadeModal('.edit-modal')
                        // $('.edit-modal').fadeOn();

                };
                options.error = function() {
                    setAlert('系统繁忙，请刷新重试');
                };
                $.ajax(options);

            })
            /**
             * [业务开支有无]
             */
        $('.edit-modal').on('click', '.e-coo-check', function() {
                var _self = $(this);
                if (_self.hasClass('on_check')) {
                    _self.removeClass('on_check');
                } else {
                    _self.addClass('on_check');
                }
            })
            /**
             * [增加收款项]
             */
        $('.edit-modal').on('click', '.e-c-add', function() {
        	//alert(111)
            var content = '<li class="form-control">' +
                '<span class="input-title">收款日期：</span>' +
                '<input type="text" value="" class="e-c-date input-text-short">' +
                '<span class="">收款金额：</span>' +
                '<input type="text" value="" class="e-c-money input-text-short">' +
                '<span class="money-unit">万元</span>' +
                '<span class="e-delete e-c-delete">删除</span>' + '</li>';
            $('.e-collection').append(content);
        })

        /**
         * [增加发票项]
         */
        $('.edit-modal').on('click', '.e-i-add', function() {
            var content = '<li class="form-control">' +
                '<span class="input-title">发票日期：</span>' +
                '<input type="text" value="" class="e-i-date input-text-short">' +
                '<span class="">发票金额：</span>' +
                '<input type="text" value="" class="e-i-money input-text-short">' +
                '<span class="money-unit">万元</span>' +
                '<span class="e-delete e-i-delete">删除</span>' +
                '</li>';
            $('.e-invoice').append(content);
        })

        /**
         * [增加奖金项]
         */
        $('.edit-modal').on('click', '.e-b-add', function() {
                var content = '<li class="form-control">' +
                    '<span class="input-title">奖金日期：</span>' +
                    '<input type="text" value="" class="e-b-date input-text-short ">' +
                    '<span class="">奖金金额：</span>' +
                    '<input type="text" value="" class="e-b-money input-text-short">' +
                    '<span class="money-unit">万元</span>' +
                    '<span class="">毛产值奖金金额：</span>' +
                    '<input type="text" value="" class="e-g-b-money input-text-short">' +
                    '<span class="money-unit">万元</span>' +
                    '<span class="e-delete e-b-delete">删除</span>' +
                    '</li>';
                $('.e-bonuse').append(content);
            })
            /**
             * [增加结算项]
             */
        $('.edit-modal').on('click', '.e-s-add', function() {
                var content = '<li class="form-control">' +
                    '<span class="input-title">结算日期：</span>' +
                    '<input type="text" value="" class="e-s-date input-text-short">' +
                    '<span class="">结算金额：</span>' +
                    '<input type="text" value="" class="e-s-money input-text-short">' +
                    '<span class="money-unit">万元</span>' +
                    '<span class="e-delete e-s-delete">删除</span>' +
                    '</li>';
                $('.e-statement').append(content);
            })
            /**
             * ［删除项］
             */
        $('.edit-modal').on('click', '.e-delete', function() {
            $(this).parent().remove();
        })

        //退出修改
        $('.cancel-btn').click(function() {
            $(this).parents('.widget-box').first().fadeOut();
            $('.mask').fadeOut();
        })

        //提交修改信息
        $('.update-btn').click(function() {
            var id = $('.edit-info-div').data("id");
            console.log(id);
            // 前端返回数据
            var dataJson = {
                contractParty: $('.e-belong').val(), //合同归属单位
                projectMoney: $('.e-project').val(), //项目经费
                netOutput: setGross(), //毛产值
                outsourceSum: setColMoney().cooTotal, //外协费总额
                outsources: JSON.stringify([ //外协费
                    { type: "检测费", money: setColMoney().check },
                    { type: "专家费", money: setColMoney().expert },
                    { type: "会务费", money: setColMoney().meet },
                    { type: "招待费", money: setColMoney().entertain },
                    { type: "其它", money: setColMoney().other }
                ]),
                hasService: setColMoney().flag = 1 ? true : false, //是否业务开支
                receiptSum: setCollection().cTotal, //收款总计
                receipts: JSON.stringify(setCollection().collections), //收款
                billSum: setInvoice().iTotal, //发票总计
                bills: JSON.stringify(setInvoice().invoices), //发票
                rewardSum: setBonuse().bTotal, //奖金总计
                grossRewardSum: setBonuse().gbTotal, //毛产值奖金总计
                rewards: JSON.stringify(setBonuse().bonuses), //奖金
                balanceSum: setStatement().sTotal, //结算总计
                balance: JSON.stringify(setStatement().statements), //结算
                comment: $('.comment').val() //资金备注
            }
            console.log(dataJson);
            // 请求
            var options = getBASEPUTAJAX();
            options.url = "/epi/finance/" + id;
            options.data = {
                _method: "PUT",
                contractParty: $('.e-belong').val(), //合同归属单位
                projectMoney: $('.e-project').val(), //项目经费
                //                netOutput : setGross(),//毛产值
                //                outsourceSum :  setColMoney().cooTotal,//外协费总额
                outsources: JSON.stringify([ //外协费
                    { type: "检测费", money: setColMoney().check },
                    { type: "专家费", money: setColMoney().expert },
                    { type: "会务费", money: setColMoney().meet },
                    { type: "招待费", money: setColMoney().entertain },
                    { type: "其它", money: setColMoney().other }
                ]),
                hasService: setColMoney().flag = 1 ? true : false, //是否业务开支
                receiptSum: setCollection().cTotal, //收款总计
                receipts: JSON.stringify(setCollection().collections), //收款
                billSum: setInvoice().iTotal, //发票总计
                bills: JSON.stringify(setInvoice().invoices), //发票
                rewardSum: setBonuse().bTotal, //奖金总计
                grossRewardSum: setBonuse().gbTotal, //毛产值奖金总计
                rewards: JSON.stringify(setBonuse().bonuses), //奖金
                balanceSum: setStatement().sTotal, //结算总计
                balances: JSON.stringify(setStatement().statements), //结算
                comment: $('.comment').val() //资金备注
            };
            options.success = function(data) {
                var status = data.status;
                if (status == 500) {
                    setAlert('非法操作！');
                } else if (status == 400) {
                    setAlert('修改失败！');
                } else if (status == 200) {
                    $('.edit-modal,.mask').fadeOut();
                    setAlert('修改成功');
                    viewTable(1)
                } else {
                    setAlert('系统繁忙，请刷新重试');
                }

            };
            options.error = function() {
                setAlert('系统繁忙，请刷新重试');
            };
            $.ajax(options);
        })

        // 改变毛产值
        $('.edit-modal').on('change', '.e-project,.e-coo', function() {
                setGross();
            })
            //改变外协费
        $('.edit-modal').on('change', '.e-coo', function() {
                setColMoney();
            })
            // 改变收款总计
        $('.edit-modal').on('change', '.e-c-money', function() {
                setCollection();
            })
            // 改变发票总计
        $('.edit-modal').on('change', '.e-i-money', function() {
                setInvoice();
            })
            // 改变奖金总计
        $('.edit-modal').on('change', '.e-b-money,.e-g-b-money', function() {
            setBonuse();
        })
        //改变结算总计
        $('.edit-modal').on('change', '.e-s-money', function() {
        	setStatement();
        })
        


        // 改变收款总计
        $('.edit-modal').on('click', '.e-c-delete', function() {
                //alert(1111);
                setCollection();
            })
        // 改变发票总计
        $('.edit-modal').on('click', '.e-i-delete', function() {
                setInvoice();
            })
        // 改变奖金总计
        $('.edit-modal').on('click', '.e-b-delete', function() {
            setBonuse();
        })

        // 改变结算总计
        $('.edit-modal').on('click', '.e-s-delete', function() {
            setStatement();
        })

        // 上一页
        $('.upPage').click(function() {
            var crtPageNum = $('.pagelist').data("page-num");
            var ele = $('.pagelist .ele');
            var max = ele.length;
            if (crtPageNum == 1) {
                setAlert('已至第一页')
            } else if (crtPageNum % max == 1) {
                for (var i = 0; i < max; i++) {
                    var eleLi = ele.eq(i).text();
                    ele.eq(i).text(eleLi - max);
                }
                ele.removeClass('on');
                ele.eq(max - 1).addClass('on');
                $('.pagelist').data('page-num', crtPageNum - 1);
                viewTable(crtPageNum - 1);

            } else {
                ele.removeClass('on');
                ele.eq((crtPageNum - 2) % max).addClass('on');
                $('.pagelist').data('page-num', crtPageNum - 1);
                viewTable(crtPageNum - 1);
            }
        })

        // 下一页
        $('.downPage').click(function() {
            var crtPageNum = parseInt($('.pagelist').data("page-num"));
            var nextNum = crtPageNum + 1;
            console.log(nextNum);
            var ele = $('.pagelist .ele');
            var totalNum = $('.total-page-num').text();
            var max = ele.length;
            if (crtPageNum == totalNum) {
                setAlert('已至最后一页')
            } else if (crtPageNum % max == 0) {
                for (var i = 0; i < max; i++) {
                    var eleLi = parseInt(ele.eq(i).text());
                    ele.eq(i).text(eleLi + max);
                }
                ele.removeClass('on');
                ele.eq(0).addClass('on');
                $('.pagelist').data('page-num', nextNum);
                viewTable(nextNum);
            } else {
                ele.removeClass('on');
                ele.eq(crtPageNum % max).addClass('on');
                $('.pagelist').data('page-num', nextNum);
                viewTable(nextNum);
            }

        })

        // 跳转页
        $('.go-btn').click(function() {
            var pgNum = parseInt($('.goPage').val());
            var crtPageNum = $('.pagelist').data("page-num");
            var ele = $('.pagelist .ele');
            var max = ele.length;
            var min = parseInt((pgNum - 1) / max) * max + 1;
            if (isNaN(pgNum)) {
                setAlert('请正确输入页码');
            } else if (pgNum > parseInt(totalNum) || pgNum < 1) {
                setAlert('无此页');
            } else {
                for (var i = 0; i < max; i++) {
                    ele.eq(i).text(min + i);
                }
                ele.removeClass('on');
                ele.eq((pgNum - 1) % max).addClass('on');
                $('.pagelist').data('page-num', pgNum);
                viewTable(pgNum);
            }
        })

        // 选择页
        $('.this-table').on('click','.ele',function(){
            var pgNum = parseInt($(this).text());
            var crtPageNum = $('.pagelist').data("page-num");
            var ele = $('.pagelist .ele');
            var max = ele.length;
            ele.removeClass('on');
            ele.eq((pgNum - 1) % max).addClass('on');
            $('.pagelist').data('page-num', pgNum);
            viewTable(pgNum);

        })

        // checkbox
        $('.this-table').on('click', '.view-check', function() {
            // 如果全选，去掉全选
            if (checkFlag == 1) {
                checkFlag = 0;
                $('.all-check').removeClass('on_check');
            }
            $(this).toggleClass('on_check');
        })

        //all-checkbox
        $('.this-table').on('click', '.all-check', function() {
            if (checkFlag == 0) {
                checkFlag = 1;
                $(this).addClass('on_check');
                $('.view-check').addClass('on_check');
            } else {
                checkFlag = 0;
                $(this).removeClass('on_check');
                $('.view-check').removeClass('on_check');
            }
        })



    })
    /**
     * [viewTh 显示表头]
     */
function viewTh() {
    //前端数据
    var modelName = "财务管理";
    //------------------------------------------------
    var options = getBASEGETAJAX();
    options.url = "/epi/admin/view/columns/" + modelName;
    //options.data.modelName = modelName;
    options.success = function(data) {
        console.log(data);
        var myTemplate = Handlebars.compile($("#th-template").html());
        console.log(myTemplate(data))
        $('.v-thead').html(myTemplate(data));
        viewTable();

    };
    options.error = function() {
        setAlert('系统繁忙，请刷新重试');
    };
    $.ajax(options);
}

/**
 * [viewTable 显示表格]
 * @param  {[Float]} pageNum [页码]
 * @param  {[Float]} records [每页记录数]
 */
function viewTable(pageNum, records) {
    //前端数据
    if (records == undefined) {
        records = 5;
    }
    if (pageNum == undefined) {
        pageNum = 1;
    }
    pageSum('financeview', records,function(){
        viewPageList();
    });
    pageCrt();
    var $viewTh = $('.view-th');
    var keyArr = []; //键名数组
    console.log($viewTh.length)
    for (var i = 0; i < $viewTh.length; i++) {
        keyArr.push($viewTh.eq(i).data('key'));
    }
    console.log(keyArr);
    loading();
    //------------------------------------------------
    var options = getBASEGETAJAX();
    options.url = "/epi/finance/projects/" + pageNum + "/" + records;
    options.success = function(data) {
        console.log(data);
        var content = '';
        var k = keyArr[0];

        //遍历数据
        for (var i = 0; i < data.length; i++) {
            content += '<tr>';
            content += '<th class="operate-left"><div class="checked view-check"><input type="checkbox" class="check-input"></div></th>';
            content += '<td>' + (i + 1) + '</td>'
            content
            //遍历字段
            for (var j = 0; j < keyArr.length; j++) {
                console.log(keyArr[j])
                if (data[i].hasOwnProperty(keyArr[j])) {

                    if (keyArr[j] == 'receiptSum' || keyArr[j] == 'billSum' || keyArr[j] == 'rewardSum') {
                        console.log('**************************************')
                        if (data[i][keyArr[j]] == data[i].project.projectMoney) {
                            content += '<td class="green">' + data[i][keyArr[j]] + '</td>';
                        } else {
                            content += '<td class="red">' + data[i][keyArr[j]] + '</td>';
                        }
                    } else {
                        console.log('-------------------------------------')
                        content += '<td>' + data[i][keyArr[j]] + '</td>';
                    }
                } else {
                    content += '<td>' + data[i].project[keyArr[j]] + '</td>';
                }

            }
            content += '<th class="operate">' +
                '<button class="drop-left">操作>></button>' +
                '<div class="drop-left-menu">' +
                '<li class="view-info" data-id="' + data[i].project.proid + '">查看详情</li>' +
                '<li class="edit-info" data-id="' + data[i].project.proid + '">修改财务信息</li>' +
                '</div>' +
                '</th>';
            content += '</tr>';
        }
        $('.v-body').html(content);
        loadingHide();

    };
    options.error = function() {
        setAlert('系统繁忙，请刷新重试');
    };
    $.ajax(options);

}

/**
 * [getJsonData 财务所有信息]
 * @return {[type]} [description]
 */
// function getJsonData(){
//     var belong = $('.e-belong').val(),//项目归属
//         project = $('.e-project').val(),//项目经费
// }

//设置毛产值
function setGross() {
    var gross = parseFloat($('.e-project').val()) - setColMoney().cooTotal;
    gross = checkNum(gross);
    $('.e-gross').val(gross);
    return gross;
}

//设置外协费
function setColMoney() {
    var cooTotal = 0, //外协费
        check = parseFloat($('.e-check').val()), //检测费
        expert = parseFloat($('.e-expert').val()), //专家费
        meet = parseFloat($('.e-meet').val()), //会务费
        entertain = parseFloat($('.e-entertain').val()), //招待费
        other = parseFloat($('.e-other').val()); //其它费用
    cooTotal = check + expert + meet + entertain + other;
    console.log(cooTotal)
    check = checkNum(check);
    expert = checkNum(expert);
    meet = checkNum(meet);
    entertain = checkNum(entertain);
    other = checkNum(other);
    cooTotal = checkNum(cooTotal);
    $('.e-coo-total').text(cooTotal);
    // console.log('cooTotal:'+cooTotal)
    var flag = 0; // 是否业务开支，是：1，否：0
    if ($('.e-coo-check').hasClass('on_check')) {
        flag = 1;
    }
    return {
        cooTotal: cooTotal,
        check: check,
        expert: expert,
        meet: meet,
        entertain: entertain,
        other: other,
        cooTotal: cooTotal,
        flag: flag
    }

}

//设置收款信息
function setCollection() {
    var $date = $('.e-c-date');
    var $money = $('.e-c-money');
    var cTotal = 0;
    var collections = [];
    for (var i = 0; i < $date.length; i++) {
        var money = parseFloat($money.eq(i).val());
        money = checkNum(money);
        console.log('------------------------------');
        console.log(money);
        collections.push({
            receiptDate: $date.eq(i).val(),
            money: money
        })
        cTotal += parseFloat(collections[i].money);
    }
    cTotal = checkNum(cTotal);
    $('.e-c-total').text(cTotal);
    console.log(collections)
    return {
        cTotal: cTotal,
        collections: collections
    }


}

//设置发票信息
function setInvoice() {
    var $date = $('.e-i-date');
    var $money = $('.e-i-money');
    var iTotal = 0;
    var invoices = [];
    for (var i = 0; i < $date.length; i++) {
        var money = parseFloat($money.eq(i).val());
        money = checkNum(money);
        invoices.push({
            billDate: $date.eq(i).val(),
            money: money
        })
        iTotal += parseFloat(invoices[i].money);
    }
    iTotal = checkNum(iTotal);
    $('.e-i-total').text(iTotal);

    return {
        iTotal: iTotal,
        invoices: invoices
    }
}

//设置奖金总金额
function setBonuse() {
    var bonuses = [];
    var $date = $('.e-b-date');
    var $money = $('.e-b-money');
    var $gMoney = $('.e-g-b-money');
    var bTotal = 0;
    var gbTotal = 0;
    var bonuses = [];
    for (var i = 0; i < $date.length; i++) {
        var money = parseFloat($money.eq(i).val());
        money = checkNum(money);
        var gMoney = parseFloat($gMoney.eq(i).val());
        gMoney = checkNum(gMoney);
        bonuses.push({
                rewardDate: $date.eq(i).val(),
                money: money,
                netOutputValue: gMoney
            })
            // console.log(bonuses[i].reward);
            // console.log(bonuses[i].reward);
        bTotal += parseFloat(bonuses[i].money);
        gbTotal += parseFloat(bonuses[i].netOutputValue);
    }
    bTotal = checkNum(bTotal);
    gbTotal = checkNum(gbTotal);

    $('.e-b-total').text(bTotal);
    $('.e-g-b-total').text(gbTotal);



    return {
        bTotal: bTotal,
        gbTotal: gbTotal,
        bonuses: bonuses
    }
}

//设置结算信息
function setStatement() {
    var $date = $('.e-s-date');
    var $money = $('.e-s-money');
    var sTotal = 0;
    var statements = [];
    for (var i = 0; i < $date.length; i++) {
        var money = parseFloat($money.eq(i).val());
        money = checkNum(money);
        statements.push({
            balanceDate: $date.eq(i).val(),
            money: money
        })
        sTotal += parseFloat(statements[i].money);
    }
    sTotal = checkNum(sTotal);
    $('.e-s-total').text(sTotal);

    return {
        sTotal: sTotal,
        statements: statements
    }
}

/**
 * [checkNum 检查数字]
 * @param  {[type]} num [被检查的数字]
 */
function checkNum(num) {
    if (isNaN(num)) num = 0;
    console.log(num);
    num = num.toFixed(6);
    return num;
}

/**
 * 获取总页数
 * @return {[type]} [description]
 */
function pageSum(tableName, pageSize,callback) {
    $.ajax({
        url: "/epi/common/pages",
        type: "GET",
        data: {
            tableName: tableName,
            pageSize: pageSize
        },
        dataType: 'json',
        success: function(data) {
            console.log(data.pageSum)
            totalNum = data.pageSum;
            $('.total-page-num').text(totalNum);
            callback();
        },
        error: function() {
            console.log('获取总页数失败');
        }
    })
}

function viewPageList() {
    var totalNum = parseInt($('.total-page-num').text());
    var content = '';
    var crt = $('.pagelist').data('page-num');
    if (totalNum < 8) {
        for (var i = 0; i < totalNum; i++) {
            if ((i+1) == crt) {
                content += '<li class="ele on">'+crt+'</li>';
            } else {
                content += '<li class="ele">' + (i + 1) + '</li>';
            }

        }
        $('.ele-outer').html(content)
    }
}

function pageCrt() {
    $('.crt-page-num').text($('.pagelist').data("page-num"));
}
